package com.ctg.itrdc.imageconsole.service.scheduler;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.ctg.itrdc.imageconsole.data.entity.K8sOperationRecord;
import com.ctg.itrdc.imageconsole.service.IK8sOperationRecordService;

/**
 * 
 * @description: 定时轮循操作记录表，检测操作是否完成
 * @version: v1.0.0
 * @author: Piao.Wu
 * 
 *          Modification History: Date Author Version Description
 *          -----------------------------------------------------------------
 *          2016年10月19日 上午10:15:31 Piao.Wu v1.0.0 create
 *
 */
@Component("checkExecutingRecordsScheduler")
public class CheckExecutingRecordsScheduler implements IScheduler, Runnable {

//	private static final Logger logger = LoggerFactory.getLogger(CheckExecutingRecordsScheduler.class);

	private int totalThreadCount = Runtime.getRuntime().availableProcessors() * 2;

	private ExecutorService executorService = Executors.newFixedThreadPool(totalThreadCount);

	@Resource
	private IK8sOperationRecordService k8sOperationRecordService;

	/**
	 * 获取线程池空闲线程数
	 * 
	 * @return
	 */
	private int getIdleThreadCount() {
		int activeThreadCountInPool = ((ThreadPoolExecutor) executorService).getActiveCount();
		return totalThreadCount - activeThreadCountInPool;
	}

	@Override
	public void run() {
		int idleThreadCount = getIdleThreadCount();
//		logger.debug("Thread pool idle thread count [{}]", idleThreadCount);
		if (idleThreadCount <= 0) {
			return;
		}
		List<K8sOperationRecord> list = k8sOperationRecordService.getExecutingRecords();
//		logger.info("get count of executing records is {} ", list.size());
		for (final K8sOperationRecord record : list) {
			executorService.submit(new Runnable() {
				@Override
				public void run() {
					k8sOperationRecordService.CheckExecutingRecords(record);
				}
			});
		}
	}

	public int getTotalThreadCount() {
		return totalThreadCount;
	}

	public void setTotalThreadCount(int totalThreadCount) {
		this.totalThreadCount = totalThreadCount;
	}

}
